package com.may.web.resolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.may.web.annotation.ParamFill;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Parameter;
import java.util.Map;

/**
 * @program: daimao
 * @description:
 * @author: Bobby.Ma
 * @create: 2020-09-22 10:14
 **/
@Component
public class ParamFillResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(ParamFill.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        JSONObject res = new JSONObject();
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap != null) {
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                res.put(entry.getKey(), entry.getValue()[0]);
            }
        }

        JSONObject jsonObject = JSONObject.parseObject(res.toString());
        Integer age = jsonObject.getInteger("age");
        if (age == null){
            jsonObject.put("age",18);
        }

        Parameter parameter = methodParameter.getParameter();
        Class<?> type = parameter.getType();

        return JSON.parseObject(jsonObject.toJSONString(), type);
    }
}
